<?php
/**
 * Dispatch Return Head
 */
class DRH extends AppModel {
    var $name = 'DRH';

    var $useTable = 'dispatch_return_heads';

    var $hasMany = array(
        'DR' => array(
            'foreignKey' => 'dispatch_return_head_id',
            )
    );

    var $belongsTo = array(
            'Dispatch' => array(
                'fields' => array('id', 'dispatch_no')
        ),
            'Warehouse' => array(
                'fields' => array('id', 'name')
        ),
            'Customer' => array(
                'fields' => array('id', 'cust_no', 'name')
        ),
            'Site' => array(
                'fields' => array('id', 'site_no', 'name')
        ),
            'User' => array(
                'foreignKey' => 'collector_id',
                'fields' => array('username', 'name')
        )
    );

    var $validate = array(
            'return_no' => array(
                    'notEmpty' => array(
                        'rule' => array('notEmpty'),
                        'message' => 'Return no. is required.',
                        'required' => true,
            ),
                    'isUnique' => array(
                        'rule' => 'isUnique',
                        'message' => 'Return no is already taken.',
                        'on' => 'create'
            ),
        ),
            'return_date' => array(
                    'rule' => array('date', 'dmy'),
                    'message' => 'Return date is required.',
                    'required' => true,
        ),
            'dispatch_id' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Dispatch no. is required.',
                    'required' => true,
        ),
            'customer_id' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Customer is required.',
                    'required' => true,
        ),
            'site_id' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Site is required.',
                    'required' => true,
        ),
    );

    function beforeSave() {
        if (isset($this->data['DRH']['return_date'])) {
            $this->data['DRH']['return_date'] = $this->dateFormatBeforeSave($this->data['DRH']['return_date']);
        }
        return true;
    }

    function afterFind($results) {
        foreach ($results as &$custStockOutReturnHead) {
            if (isset($custStockOutReturnHead['DRH']['return_date'])) {
                $custStockOutReturnHead['DRH']['return_date'] = $this->dateFormatAfterFind($custStockOutReturnHead['DRH']['return_date']);
            }
        }
        return $results;
    }

    /**
     * Custom Query สร้าง Query มาเองให้เป็นรูปแบบที่เหมาะสมสำหรับหน้า print
     * @param int $id cust_stock_in_head_id
     * @return array data
     */
    function findForPrintByid($id) {
        $this->contain(array('Customer', 'Site', 'Warehouse', 'Dispatch',
                'DR' => array('Product' => array('part_no', 'text', 'Unit'), 'CustProductSite' => array('stock_code'))
            )
        );
        $data = $this->findById($id);

        $this->DR->bindModel(array(
                'hasMany' => array(
                    'ProductSerial' => array(
                        'foreignKey' => 'its_stock_in_id',
                        'conditions' => array(
                            'its_stock_in_type' => DR::ITS_STOCK_IN_TYPE
                        )
                    )
                )
            )
        );

        $Product = $this->DR->Product;
        $PS = $this->DR->ProductSerial;
        $L = $PS->Location;

        // วนลูปรายการ DR
        foreach($data['DR'] as &$dr) {
            // หา Location ที่มีอยู่ใน DR รายการนี้
            $psLs = $PS->find('all', array(
                    'fields' => array('DISTINCT location_id', 'price'),
                    'conditions' => array(
                        'its_stock_in_id' => $dr['id'],
                        'its_stock_in_type' => DR::ITS_STOCK_IN_TYPE,
                        'product_id' => $dr['product_id']
                    )
                )
            );

            // แปะ Location ที่ได้เข้า DR
            foreach ($psLs as $psCl) {
                $L->contain();
                $location = $L->findById($psCl['ProductSerial']['location_id']);

                // option สำหรับ query product serial
                $options = array(
                    'contain' => array(),
                    'conditions' => array(
                        'its_stock_in_id' => $dr['id'],
                        'its_stock_in_type' => DR::ITS_STOCK_IN_TYPE,
                        'product_id' => $dr['product_id'],
                        'location_id' => $psCl['ProductSerial']['location_id'],
                        'price' => $psCl['ProductSerial']['price']
                    )
                );

                // นับจำนวนที่ stock out ใน location นี้
                $ps_count = $PS->find('count', $options);

                // ถึง เฉพาะ Product Serial ที่มี Serial no หรือ other information (ถ้าไม่มีจะออกมา 1 แถว)
                $options['fields'] = array('DISTINCT serial_no', 'other_information');
                $ps = $PS->find('all', $options);

                $location['return_qty'] = $ps_count;
                $location['price'] = $psCl['ProductSerial']['price'];
                $location['PS'] = $ps;

                $dr['ProductLocation'][] = $location;
            }
        }
        return $data;
    }
}
?>
